package com.lance.answer.question_export.gk_new;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.lance.answer.dto.GkUser;
import com.lance.answer.dto.GkUserCourseInfo;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.section_import.SectionImport;
import com.lance.answer.util.CollectionsUtil;
import com.lance.answer.util.Constant;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

// 根据学生获取url
@Slf4j
public class GetUserUrlInfoTask extends Thread {


    private final String driverPath;
    private final LinkedBlockingDeque<GkUser> users;

    public GetUserUrlInfoTask(String driverPath, LinkedBlockingDeque<GkUser> users) {
        this.driverPath = driverPath;
        this.users = users;
    }

    @SneakyThrows
    @Override
    public void run() {

        while (users.size() > 0) {
            GkUser gkUser = users.take();
            String userName = gkUser.getUsername();
            String password = gkUser.getPwd();
            log.info("任务：{} 剩余 {} 行 用户名：{} 密码：{}",
                    Thread.currentThread().getName(), users.size(), userName, password);
            System.err.println("执行任务11111");
            getCourseInfo(driverPath, gkUser);
        }

        if (users.size() == 0) {
            log.info("课程所有用户均已执行完毕，系统将在20min后结束");
            TimeUnit.MINUTES.sleep(20);
            return;
        }
    }

    public  void getCourseInfo(String driverPath, GkUser gkUser) throws Exception {
        ChromeDriver driver = Util.getDriver(driverPath);

        Map<String, String> SUBJECT = Constant.SUBJECT;

        String userName = gkUser.getUsername();
        String password = gkUser.getPwd();
        String teacher = gkUser.getTeacher();


        String url = "http://passport.ouchn.cn/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dstudentspace%26redirect_uri%3Dhttp%253A%252F%252Fstudent.ouchn.cn%252F%2523%252Fsignin-oidc%2523%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520ouchnuser%2520ouchnstudentspaceapi%2520offline_access%26state%3Dca1cb5d0270b49fdaea508b8a846c457%26nonce%3Dd257df51b0a141ac8ed35b1caf59ef4c";
        driver.get(url);
        Thread.sleep(3000);
        Util.login(driver, userName, password);

        Thread.sleep(1000);
        Util.switchToFirst(driver);



        // d://newAnswer//
        List<String> names = Lists.newArrayList();
        for(File f1:new File("libs//courseUrlInfo").listFiles()){


            System.err.println(">>>>>"+f1);
            String name = f1.getName();
            names.add(name.substring(0,name.length()-4));
        }


        List<GkUserCourseInfo> infoList = null ;
        String filePath = "libs//userCourseInfo//"+teacher;
        for (File file : Objects.requireNonNull(new File(filePath).listFiles())) {
            if (file.getName().contains(userName)&&file.length()>10) {
                try {
                    infoList=  JSON.parseArray(IOUtils.toString(new FileInputStream(file),
                            StandardCharsets.UTF_8), GkUserCourseInfo.class);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        if(infoList ==null){
            return;
        }

        List<String> courseNameList = Lists.newArrayList();
        infoList.forEach(e->courseNameList.add(e.getCourseName()));




        for (String courName : courseNameList) {
            if(names.contains(courName)){
                continue;
            }

            Util.switchToFirst(driver);


            try {



                //chromeDriver.navigate().refresh();
                for (WebElement we : driver.findElements(By.className("media-body"))) {
                    Util.switchToFirst(driver);
                    // 找到管理学基础
                    String mediaTitle = we.findElement(By.className("media-title")).getText();
                    if (!mediaTitle.contains(courName)) {
                        continue;
                    }
                    try {
                        //点击进入学习的按钮
                        WebElement studyButton = we.findElement(By.cssSelector("button[class='btn bg-primary']"));
                        studyButton.click();
                        //Util.switchToLast(driver);
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        try {
                            driver.close();
                            driver.quit();
                        } catch (Exception e2) {

                        }
                    }
                }

                Util.switchToLast(driver);
                // 关闭其他页面，只留下当前课程页面
                Set<Cookie> cookies = driver.manage().getCookies();
                String token = "";
                for (Cookie c : cookies) {
                    if("MoodleSession".equals(c.getName())){
                        token = c.getValue();
                    }
                }
                System.err.println("token:"+token);
                //

                Document doc = SectionImport.getDocument(driver.getCurrentUrl(),userName,token);
                Elements courses = doc.getElementsByClass("course-content");
                //System.out.println(courses.toString());

                if (CollectionsUtil.isEmpty(courses)) {
                    System.out.println("为空");
                    return;
                }
                Element course = courses.get(0);
                int sectionCount = 100;
                List<String> lines = new ArrayList<>();
                for (int i = 2;i <= sectionCount;i++) {
                    Element section = course.getElementById("section-" + i);
                    //System.out.println(section.toString());
                    if (null != section) {
                        Elements instances = section.select("a[class=aalink]");
                        for (Element instance:instances) {
                            String href = instance.attr("href");
                            String instanceName = instance.getElementsByClass("instancename").get(0).ownText();
                            String line = String.format("%s,%s",href,instanceName);
                            System.out.println(line);
                            // FIXME
                            lines.add(line);
//                            if(line.contains("形考任务")){
//                                lines.add(line);
//                            }
                            // FIXME
                        }
                        System.out.println("\n");
                        System.out.println("\n");
                        System.out.println("-----------------------------------------");
                    }
                }
                File file = new File("libs//courseUrlInfo//"+courName+".txt");
                FileUtils.writeLines(file,lines);

                Thread.sleep(2000);

                //  FileUtils.write(new File("d://newAnswer//" + subjectName + ".json"), JSONObject.toJSONString(answers, SerializerFeature.PrettyFormat), "utf-8");

                driver.close();
                Util.switchToFirst(driver);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        Thread.sleep(2000);
        driver.quit();
    }


}
